package cn.toma.controller.sys;

import cn.toma.common.annotation.Log;
import cn.toma.common.exception.FfBootException;
import cn.toma.common.vo.StringPool;
import cn.toma.config.web.utli.BaseController;
import cn.toma.model.sys.Dict;
import cn.toma.service.sys.DictService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Map;

@Slf4j
@Validated
@RestController
@RequestMapping("dict")
public class DictController extends BaseController
{

	private String message;

	@Autowired
	private DictService dictService;

	@GetMapping
	@RequiresPermissions("dict:view")
	public Map<String, Object> DictList(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "10") int pageSize, Dict dict)
	{
		Page<Dict> objects = PageHelper.startPage(pageNum, pageSize);
		this.dictService.findDicts(dict);
		return getDataTable(objects.toPageInfo());
	}

	@Log("新增字典")
	@PostMapping
	@RequiresPermissions("dict:add")
	public void addDict(@Valid Dict dict) throws FfBootException
	{
		try {
			this.dictService.createDict(dict);
		} catch (Exception e) {
			message = "新增字典成功";
			log.error(message, e);
			throw new FfBootException(message);
		}
	}

	@Log("删除字典")
	@DeleteMapping("/{dictIds}")
	@RequiresPermissions("dict:delete")
	public void deleteDicts(@NotBlank(message = "{required}") @PathVariable String dictIds) throws FfBootException
	{
		try {
			String[] ids = dictIds.split(StringPool.COMMA);
			this.dictService.deleteDicts(ids);
		} catch (Exception e) {
			message = "删除字典成功";
			log.error(message, e);
			throw new FfBootException(message);
		}
	}

	@Log("修改字典")
	@PutMapping
	@RequiresPermissions("dict:update")
	public void updateDict(@Valid Dict dict) throws FfBootException
	{
		try {
			this.dictService.updateDict(dict);
		} catch (Exception e) {
			message = "修改字典成功";
			log.error(message, e);
			throw new FfBootException(message);
		}
	}

//    @PostMapping("excel")
//    @RequiresPermissions("dict:export")
//    public void export(QueryRequest request, Dict dict, HttpServletResponse response) throws FfBootException {
//        try {
//            List<Dict> dicts = this.dictService.findDicts(request, dict).getRecords();
//            ExcelKit.$Export(Dict.class, response).downXlsx(dicts, false);
//        } catch (Exception e) {
//            message = "导出Excel失败";
//            log.error(message, e);
//            throw new FfBootException(message);
//        }
//    }
}
